package com.sayice.icemusic.service.music.impl.proxy;

import com.sayice.icemusic.pojo.Music;
import com.sayice.icemusic.service.cache.CacheService;
import com.sayice.icemusic.service.music.MusicService;
import com.sayice.icemusic.service.music.impl.CloudMusicServiceImpl;
import com.sayice.icemusic.service.music.impl.KuGouMusicServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 音乐服务缓存代理
 *
 * @author shubing
 */
@Component
public class MusicServiceProxy implements MusicService {
    private final String CACHE_NAME = "songsCache";
    
    private final CloudMusicServiceImpl cloudMusicService = CloudMusicServiceImpl.getInstance();
    private final KuGouMusicServiceImpl kuGouMusicService = KuGouMusicServiceImpl.getInstance();
    
    @Autowired
    private CacheService cacheService;
    
    /**
     * 搜索音乐
     *
     * @param name 音乐名
     * @return 搜索到的音乐列表
     */
    @Override
    public List<Music> search(String name, String sorter) {
        List<Music> musicList = new ArrayList<>();
        try {
            musicList = new ArrayList<>(cacheService.getListFromHash(CACHE_NAME, name, Music.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (musicList.isEmpty()) {
            musicList.addAll(cloudMusicService.search(name, sorter));
            musicList.addAll(kuGouMusicService.search(name, sorter));
            addCache(name, musicList);
        }
        return musicList;
    }
    
    /**
     * 获取歌词
     *
     * @param musicId    音乐 id
     * @param sourceName 来源
     * @return 返回歌词信息数组：[[第一句的时间，第一句的内容], [第二句的时间，第二句的内容]……]
     */
    @Override
    public String[][] getLyrics(String musicId, String sourceName) {
        switch (sourceName) {
            case "网易云音乐":
                return cloudMusicService.getLyrics(musicId, sourceName);
            case "酷狗音乐":
                return kuGouMusicService.getLyrics(musicId, sourceName);
            default:
                return new String[0][];
        }
    }
    
    /**
     * 将搜索结果添加到缓存
     *
     * @param name      搜索名
     * @param musicList 搜索到的音乐列表
     */
    @Async("taskExecutor")
    public void addCache(String name, List<Music> musicList) {
        try {
            cacheService.addHash(CACHE_NAME, name, musicList, 1, TimeUnit.DAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
